package com.lm.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version 1.0
 * @dscription:TODO
 * @author32477
 * @date 2025/9/19 9:00
 */
public final class WebSocketUtils {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 存储 websocket session
    public static final Map<String, Session> USER_SESSIONS = new ConcurrentHashMap<>();

    /** 
     * @description:
     * @param: session
    message 
     * @return: void 
     * @author 32477
     * @date: 2025/9/19 11:35
     */ 
    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
            logger.error("sendMessage IOException ",e);
        }
    }

    /**
     * 推送消息到其他客户端
     * @param message
     */
    public static void sendMessageAll(String message) {
        USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
    }
    
    /**
     * 向特定用户发送消息
     * @param username 目标用户名
     * @param message 消息内容
     * @return 是否发送成功
     */
    public static boolean sendMessageToUser(String username, String message) {
        Session session = USER_SESSIONS.get(username);
        if (session != null && session.isOpen()) {
            // 发送消息 
            sendMessage(session, message);
            return true;
        }
        return false;
    }
    
    /**
     * 发送对象消息
     * @param session 用户会话
     * @param obj 消息对象
     */
    public static void sendObjectMessage(Session session, Object obj) {
        try {
            String message = objectMapper.writeValueAsString(obj);
            sendMessage(session, message);
        } catch (Exception e) {
            logger.error("sendObjectMessage error", e);
        }
    }
    
    /**
     * 向特定用户发送对象消息
     * @param username 目标用户名
     * @param obj 消息对象
     * @return 是否发送成功
     */
    public static boolean sendObjectMessageToUser(String username, Object obj) {
        Session session = USER_SESSIONS.get(username);
        if (session != null && session.isOpen()) {
            sendObjectMessage(session, obj);
            return true;
        }
        return false;
    }

}
